package com.jzy.gulimall.authserver.controller;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ReflectUtil;
import com.jzy.common.constant.AuthServerConstant;
import com.jzy.common.constant.CartConstant;
import com.jzy.common.utils.CookieUtil;
import com.jzy.common.utils.R;
import com.jzy.common.vo.MemberRespVo;
import com.jzy.gulimall.authserver.feign.CartFeignService;
import com.jzy.gulimall.authserver.feign.MemberFeignService;
import com.jzy.gulimall.authserver.vo.SocialUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import weibo4j.Oauth;
import weibo4j.http.AccessToken;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;

/**
 * @author jzy
 * @date 2020/9/17 14:20
 * 处理社交登录请求
 */
@Controller
public class OAuth2Controller {

    @Resource
    private MemberFeignService memberFeignService;

    @Resource
    private CartFeignService cartFeignService;

    /**
     * 微博登录 code换取token以及用户信息
     * 合并购物车
     */
    // TODO: 2020/9/19 频繁登录,redis频繁创建session
    @GetMapping("/auth2/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletRequest request) {
        String token = "";
        try {
            Oauth oauth = new Oauth();
            //授权码换取access_token
            AccessToken accessTokenByCode = oauth.getAccessTokenByCode(code);
            Field field = ReflectUtil.getField(AccessToken.class, "uid");
            field.setAccessible(true);
            String uid = (String) field.get(accessTokenByCode);

            SocialUser socialUser = new SocialUser();
            socialUser.setAccessToken(accessTokenByCode.getAccessToken());
            socialUser.setExpireIn(accessTokenByCode.getExpireIn());
            socialUser.setUid(uid);
            R r = memberFeignService.weiboLogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                String userKey = CookieUtil.getCookieValue(request, CartConstant.TEMP_USER_COOKIE_NAME, false);
                R cart = cartFeignService.mergeCart(userKey, data.getId());
                if (cart.getCode() == 0) {
                    return "redirect:http://gulimall.com";
                } else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            }
            //重定向,携带token
            //token = JwtUtil.createToken(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
